package projet.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import projet.entity.Client;
import projet.entity.Session;
import projet.service.AddClientService;

/**
 * Servlet implementation class AddClientServlet
 */
public class AddClientServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private AddClientService addClientService = new AddClientService();
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddClientServlet() {
        super();
        // Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String sessionId = request.getParameter("sessionId");
		Session session = addClientService.getSession(Long.parseLong(sessionId));
		
		String lastname = request.getParameter("lastname");
		String firstname = request.getParameter("firstname");
		String address = request.getParameter("address");
		String phone = request.getParameter("phone");
		String email = request.getParameter("email");
		
		request.setAttribute("areEmpty", false);
		if (lastname.isEmpty() || firstname.isEmpty() || address.isEmpty() || phone.isEmpty()) {
			request.setAttribute("areEmpty", true);
			request.setAttribute("session", session);
			RequestDispatcher dispatcher = request.getRequestDispatcher("subscriptionform.jsp");
			dispatcher.forward(request, response);
			return;
		} else {
			Client client = new Client();
			client.setLastname(lastname);
			client.setFirstname(firstname);
			client.setAddress(address);
			client.setPhone(phone);
			client.setEmail(email);
			client.setSession(session);
			addClientService.addClient(client);
			RequestDispatcher dispatcher = request.getRequestDispatcher("addok.jsp");
			dispatcher.forward(request, response);
			return;
		}
		
	}

}
